package role

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateLogic) Update(req *types.Role) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)
	// 1.角色是否存在
	one, err := l.svcCtx.RoleModel.FindOne(l.ctx, req.Id)
	switch err {
	case nil:
	case model.ErrNotFound:
		fmt.Printf("[Error]角色[%d]不存在\n", req.Id)
		resp.Code = http.StatusBadRequest
		resp.Msg = "角色不存在"
		return resp, nil
	default:
		fmt.Printf("[Error]查询角色[%d]信息:%s\n", req.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.角色名称是否重复
	name := strings.TrimSpace(req.Name)
	if one.Name != name {
		var count int64
		count, err = l.svcCtx.RoleModel.Count(l.ctx, fmt.Sprintf(" where name = '%s' and id != %d", name, req.Id))
		if err != nil {
			fmt.Printf("[Error]角色[%s]查询：%s\n", name, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}

		if count > 0 {
			fmt.Printf("[Error]角色[%s]重复\n", name)
			resp.Code = http.StatusBadRequest
			resp.Msg = "角色重复"
			return resp, nil
		}
	}

	//3.更新入库
	err = l.svcCtx.RoleModel.Update(l.ctx, &model.Role{
		Id:     req.Id,
		Status: req.Status,
		SortId: req.SortId,
		Name:   name,
		Remark: strings.TrimSpace(req.Remark),
	})
	if err != nil {
		fmt.Printf("[Error]角色[%d]更新：%s\n", req.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"

	return resp, nil
}
